<template>
  <view class="container">

    <!-- 根据状态显示不同内容 -->
    <view v-if="!showQuestionnaire">
      <!-- 主内容区域 -->
      <view class="content">
      <!-- 问候语 -->
      <view class="greeting">
        <text class="greeting-text">Hi! {{ greetingName }}{{ loginStatus && loginStatus.userType === 'doctor' ? ' 医生' : '' }}</text>
        <!-- 已移除头像图片 -->
      </view>

        <!-- 抑郁量表图片 -->
        <view class="scale-image-container">
          <image class="scale-image" src="/images/抑郁量表.png" mode="aspectFill"></image>
        </view>

        <!-- 欢迎信息 -->
        <view class="welcome-text">
          <text class="welcome-title">欢迎进入，
汉密尔顿抑郁量表测试！</text>
          <text class="welcome-desc">我们将使用通过 17 个提问
记录受访者最近一周的抑郁症状，
为了保证结果的准确性，
请您根据实际情况在最符合的选项上打"√"</text>
        </view>

        <!-- 用户协议 -->
        <view class="agreement">
          <view class="checkbox-container" @click="toggleAgreement">
            <view class="checkbox" :class="{ 'checked': isAgreed }"></view>
          </view>
          <text class="agreement-text">我已阅读并且同意用户协议</text>
        </view>

        <!-- 开始按钮 -->
        <button class="start-button" :disabled="!isAgreed" @click="startAssessment">开始作答</button>
      </view>
    </view>

    <!-- 问卷部分 -->
    <view v-else class="questionnaire">
      <!-- 顶部标题 -->
      <view class="questionnaire-header">
        <text class="questionnaire-title">汉密尔顿抑郁量表</text>
        <view class="page-indicator">
            <view class="page-number" :class="{ 'active': currentPage === 1 }">1</view>
            <view class="page-number" :class="{ 'active': currentPage === 2 }">2</view>
            <view class="page-number" :class="{ 'active': currentPage === 3 }">3</view>
          </view>
        <view class="save-button">
          <image src="/static/logo.png" class="save-icon"></image>
        </view>
      </view>

      <!-- 问卷内容 -->
      <view class="questionnaire-content">
        <view class="test-items">
          <!-- 第一页：项目1-6 -->
          <view v-if="currentPage === 1">
            <!-- 项目1：抑郁情绪 -->
            <view class="test-item">
              <text class="item-title">1. 抑郁情绪</text>
              <view class="score-options">
                <radio-group @change="changeScore(0, $event)">
                  <label class="score-option"><radio color="#20b2aa" :value="0" :checked="scores[0] === 0" />0分：无</label>
                  <label class="score-option"><radio color="#20b2aa" :value="1" :checked="scores[0] === 1" />1分：只有问到才叙述</label>
                  <label class="score-option"><radio color="#20b2aa" :value="2" :checked="scores[0] === 2" />2分：在谈话中自发表达</label>
                  <label class="score-option"><radio color="#20b2aa" :value="3" :checked="scores[0] === 3" />3分：不用言语也可从表情、姿势、声音中流露出这种情绪</label>
                  <label class="score-option"><radio color="#20b2aa" :value="4" :checked="scores[0] === 4" />4分：病人的自发语言和非语言表达几乎完全表现为这种情绪</label>
                </radio-group>
              </view>
            </view>

            <!-- 项目2：有罪感 -->
            <view class="test-item">
              <text class="item-title">2. 有罪感</text>
              <view class="score-options">
                <radio-group @change="changeScore(1, $event)">
                  <label class="score-option"><radio color="#20b2aa" :value="0" :checked="scores[1] === 0" />0分：无</label>
                  <label class="score-option"><radio color="#20b2aa" :value="1" :checked="scores[1] === 1" />1分：责备自己，感到自己连累他人</label>
                  <label class="score-option"><radio color="#20b2aa" :value="2" :checked="scores[1] === 2" />2分：认为自己犯了罪，或反复思考以往的过失和错误</label>
                  <label class="score-option"><radio color="#20b2aa" :value="3" :checked="scores[1] === 3" />3分：认为目前疾病是对自己错误的惩罚，或有罪恶妄想</label>
                  <label class="score-option"><radio color="#20b2aa" :value="4" :checked="scores[1] === 4" />4分：罪恶妄想伴有指责或威胁性幻觉</label>
                </radio-group>
              </view>
            </view>

            <!-- 项目3：自杀 -->
            <view class="test-item">
              <text class="item-title">3. 自杀</text>
              <view class="score-options">
                <radio-group @change="changeScore(2, $event)">
                  <label class="score-option"><radio color="#20b2aa" :value="0" :checked="scores[2] === 0" />0分：无</label>
                  <label class="score-option"><radio color="#20b2aa" :value="1" :checked="scores[2] === 1" />1分：觉得活着没有意思</label>
                  <label class="score-option"><radio color="#20b2aa" :value="2" :checked="scores[2] === 2" />2分：希望自己已经死去，或常想到与死有关的事</label>
                  <label class="score-option"><radio color="#20b2aa" :value="3" :checked="scores[2] === 3" />3分：消极观念（自杀念头）</label>
                  <label class="score-option"><radio color="#20b2aa" :value="4" :checked="scores[2] === 4" />4分：有严重自杀行为</label>
                </radio-group>
              </view>
            </view>

            <!-- 项目4：入睡困难 -->
            <view class="test-item">
              <text class="item-title">4. 入睡困难</text>
              <view class="score-options">
                <radio-group @change="changeScore(3, $event)">
                  <label class="score-option"><radio color="#20b2aa" :value="0" :checked="scores[3] === 0" />0分：无</label>
                  <label class="score-option"><radio color="#20b2aa" :value="1" :checked="scores[3] === 1" />1分：主诉有时有入睡困难，即上床后半小时仍不能入睡</label>
                  <label class="score-option"><radio color="#20b2aa" :value="2" :checked="scores[3] === 2" />2分：主诉每晚均入睡困难</label>
                </radio-group>
              </view>
            </view>

            <!-- 项目5：睡眠不深 -->
            <view class="test-item">
              <text class="item-title">5. 睡眠不深</text>
              <view class="score-options">
                <radio-group @change="changeScore(4, $event)">
                  <label class="score-option"><radio color="#20b2aa" :value="0" :checked="scores[4] === 0" />0分：无</label>
                  <label class="score-option"><radio color="#20b2aa" :value="1" :checked="scores[4] === 1" />1分：睡眠浅多噩梦</label>
                  <label class="score-option"><radio color="#20b2aa" :value="2" :checked="scores[4] === 2" />2分：半夜（晚12点以前）曾醒来（不包括上厕所）</label>
                </radio-group>
              </view>
            </view>

            <!-- 项目6：早醒 -->
            <view class="test-item">
              <text class="item-title">6. 早醒</text>
              <view class="score-options">
                <radio-group @change="changeScore(5, $event)">
                  <label class="score-option"><radio color="#20b2aa" :value="0" :checked="scores[5] === 0" />0分：无</label>
                  <label class="score-option"><radio color="#20b2aa" :value="1" :checked="scores[5] === 1" />1分：有早醒，比平时早醒1小时，但能重新入睡</label>
                  <label class="score-option"><radio color="#20b2aa" :value="2" :checked="scores[5] === 2" />2分：早醒后无法重新入睡</label>
                </radio-group>
              </view>
            </view>
          </view>

          <!-- 第二页：项目7-12 -->
          <view v-if="currentPage === 2">
            <!-- 项目7：工作兴趣 -->
            <view class="test-item">
              <text class="item-title">7. 工作兴趣</text>
              <view class="score-options">
                <radio-group @change="changeScore(6, $event)">
                  <label class="score-option"><radio color="#20b2aa" :value="0" :checked="scores[6] === 0" />0分：无变化</label>
                  <label class="score-option"><radio color="#20b2aa" :value="1" :checked="scores[6] === 1" />1分：提问时才诉述，可能有</label>
                  <label class="score-option"><radio color="#20b2aa" :value="2" :checked="scores[6] === 2" />2分：自发地直接或间接表达对活动、工作或学习失去兴趣</label>
                  <label class="score-option"><radio color="#20b2aa" :value="3" :checked="scores[6] === 3" />3分：活动时间减少或成效降低（但仍参加活动，在食物旁待着）</label>
                  <label class="score-option"><radio color="#20b2aa" :value="4" :checked="scores[6] === 4" />4分：因目前的疾病停止工作</label>
                </radio-group>
              </view>
            </view>

            <!-- 项目8：迟缓 -->
            <view class="test-item">
              <text class="item-title">8. 迟缓</text>
              <view class="score-options">
                <radio-group @change="changeScore(7, $event)">
                  <label class="score-option"><radio color="#20b2aa" :value="0" :checked="scores[7] === 0" />0分：无</label>
                  <label class="score-option"><radio color="#20b2aa" :value="1" :checked="scores[7] === 1" />1分：精神检查中发现轻度迟缓</label>
                  <label class="score-option"><radio color="#20b2aa" :value="2" :checked="scores[7] === 2" />2分：精神检查中发现明显的迟缓</label>
                  <label class="score-option"><radio color="#20b2aa" :value="3" :checked="scores[7] === 3" />3分：精神检查困难</label>
                  <label class="score-option"><radio color="#20b2aa" :value="4" :checked="scores[7] === 4" />4分：完全不能回答问题（木僵）</label>
                </radio-group>
              </view>
            </view>

            <!-- 项目9：激越 -->
            <view class="test-item">
              <text class="item-title">9. 激越</text>
              <view class="score-options">
                <radio-group @change="changeScore(8, $event)">
                  <label class="score-option"><radio color="#20b2aa" :value="0" :checked="scores[8] === 0" />0分：无</label>
                  <label class="score-option"><radio color="#20b2aa" :value="1" :checked="scores[8] === 1" />1分：检查时，有时表现得有些心神不定</label>
                  <label class="score-option"><radio color="#20b2aa" :value="2" :checked="scores[8] === 2" />2分：明显的心神不定或小动作</label>
                  <label class="score-option"><radio color="#20b2aa" :value="3" :checked="scores[8] === 3" />3分：不能静坐，检查中曾起立</label>
                  <label class="score-option"><radio color="#20b2aa" :value="4" :checked="scores[8] === 4" />4分：搓手，咬手指，扯头发，咬嘴唇</label>
                </radio-group>
              </view>
            </view>

            <!-- 项目10：精神性焦虑 -->
            <view class="test-item">
              <text class="item-title">10. 精神性焦虑</text>
              <view class="score-options">
                <radio-group @change="changeScore(9, $event)">
                  <label class="score-option"><radio color="#20b2aa" :value="0" :checked="scores[9] === 0" />0分：无</label>
                  <label class="score-option"><radio color="#20b2aa" :value="1" :checked="scores[9] === 1" />1分：问及吋诉述</label>
                  <label class="score-option"><radio color="#20b2aa" :value="2" :checked="scores[9] === 2" />2分：自发地表达</label>
                  <label class="score-option"><radio color="#20b2aa" :value="3" :checked="scores[9] === 3" />3分：表情和言谈流露出明显忧虑</label>
                  <label class="score-option"><radio color="#20b2aa" :value="4" :checked="scores[9] === 4" />4分：明显惊恐</label>
                </radio-group>
              </view>
            </view>

            <!-- 项目11：躯体性焦虑 -->
            <view class="test-item">
              <text class="item-title">11. 躯体性焦虑</text>
              <view class="score-options">
                <radio-group @change="changeScore(10, $event)">
                  <label class="score-option"><radio color="#20b2aa" :value="0" :checked="scores[10] === 0" />0分：无</label>
                  <label class="score-option"><radio color="#20b2aa" :value="1" :checked="scores[10] === 1" />1分：轻度（可能有，模糊）</label>
                  <label class="score-option"><radio color="#20b2aa" :value="2" :checked="scores[10] === 2" />2分：中度，有肯定的上述症状</label>
                  <label class="score-option"><radio color="#20b2aa" :value="3" :checked="scores[10] === 3" />3分：重度，上述症状严重，影响生活或需加处理</label>
                  <label class="score-option"><radio color="#20b2aa" :value="4" :checked="scores[10] === 4" />4分：严重影响生活和活动</label>
                </radio-group>
              </view>
            </view>

            <!-- 项目12：胃肠道症状 -->
            <view class="test-item">
              <text class="item-title">12. 胃肠道症状</text>
              <view class="score-options">
                <radio-group @change="changeScore(11, $event)">
                  <label class="score-option"><radio color="#20b2aa" :value="0" :checked="scores[11] === 0" />0分：无</label>
                  <label class="score-option"><radio color="#20b2aa" :value="1" :checked="scores[11] === 1" />1分：食欲减退，但不需他人鼓励便自行进食</label>
                  <label class="score-option"><radio color="#20b2aa" :value="2" :checked="scores[11] === 2" />2分：进食需他人催促或请求，或需要应用泻药或助消化药</label>
                </radio-group>
              </view>
            </view>
          </view>

          <!-- 第三页：项目13-17 -->
          <view v-if="currentPage === 3">
            <!-- 项目13：全身症状 -->
            <view class="test-item">
              <text class="item-title">13. 全身症状</text>
              <view class="score-options">
                <radio-group @change="changeScore(12, $event)">
                  <label class="score-option"><radio color="#20b2aa" :value="0" :checked="scores[12] === 0" />0分：无</label>
                  <label class="score-option"><radio color="#20b2aa" :value="1" :checked="scores[12] === 1" />1分：四肢、背或颈部沉重感，背痛，头痛，肌肉疼痛，全身乏力或疲倦</label>
                  <label class="score-option"><radio color="#20b2aa" :value="2" :checked="scores[12] === 2" />2分：症状明显，影响生活</label>
                </radio-group>
              </view>
            </view>

            <!-- 项目14：性症状 -->
            <view class="test-item">
              <text class="item-title">14. 性症状</text>
              <view class="score-options">
                <radio-group @change="changeScore(13, $event)">
                  <label class="score-option"><radio color="#20b2aa" :value="0" :checked="scores[13] === 0" />0分：无</label>
                  <label class="score-option"><radio color="#20b2aa" :value="1" :checked="scores[13] === 1" />1分：轻度</label>
                  <label class="score-option"><radio color="#20b2aa" :value="2" :checked="scores[13] === 2" />2分：重度，上述症状严重，影响生活或需加处理</label>
                  <label class="score-option"><radio color="#20b2aa" :value="3" :checked="scores[13] === 3" />3分：不能肯定，或该项对被评者不适合（该项不计入总分）</label>
                </radio-group>
              </view>
            </view>

            <!-- 项目15：疑病 -->
            <view class="test-item">
              <text class="item-title">15. 疑病</text>
              <view class="score-options">
                <radio-group @change="changeScore(14, $event)">
                  <label class="score-option"><radio color="#20b2aa" :value="0" :checked="scores[14] === 0" />0分：无</label>
                  <label class="score-option"><radio color="#20b2aa" :value="1" :checked="scores[14] === 1" />1分：对身体过分关注（只是想一想就过了）</label>
                  <label class="score-option"><radio color="#20b2aa" :value="2" :checked="scores[14] === 2" />2分：反复思考健康问题（怀疑有病）</label>
                  <label class="score-option"><radio color="#20b2aa" :value="3" :checked="scores[14] === 3" />3分：重有疑病妄想（反复检查）</label>
                  <label class="score-option"><radio color="#20b2aa" :value="4" :checked="scores[14] === 4" />4分：伴幻觉的疑病妄想</label>
                </radio-group>
              </view>
            </view>

            <!-- 项目16：体重减轻 -->
            <view class="test-item">
              <text class="item-title">16. 体重减轻</text>
              <view class="score-options">
                <radio-group @change="changeScore(15, $event)">
                  <label class="score-option"><radio color="#20b2aa" :value="0" :checked="scores[15] === 0" />0分：无变化</label>
                  <label class="score-option"><radio color="#20b2aa" :value="1" :checked="scores[15] === 1" />1分：一周内体重减轻1斤以上</label>
                  <label class="score-option"><radio color="#20b2aa" :value="2" :checked="scores[15] === 2" />2分：一周内体重减轻2斤以上</label>
                </radio-group>
              </view>
            </view>

            <!-- 项目17：自知力 -->
            <view class="test-item">
              <text class="item-title">17. 自知力</text>
              <view class="score-options">
                <radio-group @change="changeScore(16, $event)">
                  <label class="score-option"><radio color="#20b2aa" :value="0" :checked="scores[16] === 0" />0分：知道自己有病，表现为忧郁</label>
                  <label class="score-option"><radio color="#20b2aa" :value="1" :checked="scores[16] === 1" />1分：知道自己有病，但归因子伙食太差、环境问题、工作过忙、病毒感染或需要休息等</label>
                  <label class="score-option"><radio color="#20b2aa" :value="2" :checked="scores[16] === 2" />2分：完全否认有病</label>
                </radio-group>
              </view>
            </view>
          </view>
        </view>

        <!-- 导航按钮 -->
        <view class="navigation-buttons">
          <!-- 第一页只显示下一页，第二页显示上一页和下一页，第三页只显示上一页 -->
          <button class="nav-button" @click="prevPage" v-if="currentPage > 1">上一页</button>
          <button class="nav-button" @click="nextPage" v-if="currentPage < totalPages">下一页</button>
        </view>

        <!-- 提交按钮 -->
        <button class="submit-button" @click="submitTest" v-if="currentPage === totalPages">测试提交</button>
        <view class="confirm-checkbox" v-if="currentPage === totalPages">
          <checkbox :checked="confirmSubmit" @tap="confirmSubmit = !confirmSubmit" />确认提交即同意评估结果
        </view>
        
        <!-- 滚动到顶部按钮 -->
        <button class="scroll-top-button" @click="scrollToTop" v-if="showQuestionnaire">
          ↑ 返回顶部
        </button>
      </view>
  </view>
</view>
</template>

<script>
  import { getLoginStatus } from '../../../utils/auth.js';
  import { createAssessment, submitHamd17 } from '../../../utils/api/doctor.js';
  
  export default {
    data() {
      return {
        isAgreed: false,
        showQuestionnaire: false,
        currentPage: 1,
        totalPages: 3,
        confirmSubmit: false,
        scores: Array(17).fill(null), // 17个测试项目，初始化为null，避免默认选中
        loginStatus: null,
        greetingName: '用户',
        assessmentId: null, // 评估记录ID
        patientId: null // 患者ID
      }
    },
    
    onLoad(options) {
      // 页面加载时获取登录状态和用户信息
      this.loginStatus = getLoginStatus();
      
      // 接收评估ID或患者ID
      if (options.assessmentId) {
        this.assessmentId = parseInt(options.assessmentId);
        console.log('接收到评估ID:', this.assessmentId);
      }
      if (options.patientId) {
        this.patientId = parseInt(options.patientId);
        console.log('接收到患者ID:', this.patientId);
      }
      
      // 提取用户姓名用于问候，按优先级获取：wechat_name > nickname > name > realName
      if (this.loginStatus.userInfo) {
        this.greetingName = this.loginStatus.userInfo.wechat_name || 
                           this.loginStatus.userInfo.nickname || 
                           this.loginStatus.userInfo.name || 
                           this.loginStatus.userInfo.realName || 
                           '用户';
        console.log('抑郁量表页面用户信息:', this.loginStatus.userInfo);
        console.log('设置的问候姓名:', this.greetingName);
      }
      
      // 如果没有传患者ID，使用当前用户ID（患者自己填写）
      if (!this.patientId && this.loginStatus.userInfo) {
        this.patientId = this.loginStatus.userInfo.id;
      }
    },
    methods: {
      // 返回上一页
      navigateBack() {
        if (this.showQuestionnaire) {
          this.showQuestionnaire = false;
        } else {
          uni.navigateBack();
        }
      },
      
      // 滚动到顶部
      scrollToTop() {
        // 使用uni-app的原生方法实现直接跳转到顶部，不带动画效果
        uni.pageScrollTo({
          scrollTop: 0,
          duration: 0
        });
      },
      
      // 切换用户协议同意状态
      toggleAgreement() {
        this.isAgreed = !this.isAgreed;
      },
      
      // 开始测试
      startAssessment() {
        if (this.isAgreed) {
          this.showQuestionnaire = true;
          this.scrollToTop();
        } else {
          uni.showToast({
            title: '请先阅读并同意用户协议',
            icon: 'none'
          });
        }
      },
      
      // 上一页
      prevPage() {
        if (this.currentPage > 1) {
          this.currentPage--;
          this.scrollToTop();
        } else {
          this.showQuestionnaire = false;
        }
      },
      
      // 下一页
      nextPage() {
        // 检查当前页的所有问题是否都已回答
        if (this.currentPage === 1) {
          // 检查第一页（问题1-6）
          for (let i = 0; i < 6; i++) {
            if (this.scores[i] === null) {
              uni.showToast({
                title: '请完成第' + (i + 1) + '题',
                icon: 'none'
              });
              return;
            }
          }
          this.currentPage++;
          this.scrollToTop();
        } else if (this.currentPage === 2) {
          // 检查第二页（问题7-12）
          for (let i = 6; i < 12; i++) {
            if (this.scores[i] === null) {
              uni.showToast({
                title: '请完成第' + (i + 1) + '题',
                icon: 'none'
              });
              return;
            }
          }
          this.currentPage++;
          this.scrollToTop();
        } else {
          // 如果已经是最后一页，点击下一页可以跳转到查看报告页面
          this.navigateToReport();
        }
      },
      
      // 提交测试
      async submitTest() {
        // 检查是否所有问题都已回答
        const allAnswered = this.scores.every(score => score !== null);
        
        if (!allAnswered) {
          uni.showToast({
            title: '请回答所有问题',
            icon: 'none'
          });
          return;
        }
        
        // 计算总分，排除第14项3分的情况
        let totalScore = 0;
        for (let i = 0; i < this.scores.length; i++) {
          if (i === 13 && this.scores[i] === 3) {
            // 第14项（数组索引13）不允许打3分
            uni.showToast({
              title: '第14项评分有误，请重新选择',
              icon: 'none'
            });
            return;
          }
          totalScore += this.scores[i] || 0;
        }
        
        try {
          // 判断是否为患者自评（没有传入patientId，或patientId等于当前用户）
          const currentUserId = this.loginStatus.userInfo?.id;
          const isSelfAssessment = !this.patientId || this.patientId === currentUserId;

          if (isSelfAssessment) {
            // ========== 患者自评：提交到后端 ==========
            console.log('患者自评模式，提交到后端');

            uni.showLoading({ title: '提交中...' });

            // 1. 创建评估记录
            const assessmentRes = await createAssessment(
              currentUserId,
              new Date().toISOString().split('T')[0], // 今天日期
              totalScore, // hamd_total
              0, // hama_total
              0  // ymrs_total
            );

            if (assessmentRes.code !== 200) {
              throw new Error(assessmentRes.msg || '创建评估记录失败');
            }

            const newAssessmentId = assessmentRes.data.assessment_id;
            console.log('患者自评记录创建成功，ID:', newAssessmentId);

            // 2. 提交HAMD17量表详情
            const hamd17Data = {
              item1_depression: this.scores[0],
              item2_guilt: this.scores[1],
              item3_suicide: this.scores[2],
              item4_sleep_initial: this.scores[3],
              item5_sleep_middle: this.scores[4],
              item6_sleep_late: this.scores[5],
              item7_activity: this.scores[6],
              item8_retardation: this.scores[7],
              item9_agitation: this.scores[8],
              item10_anxiety_psychic: this.scores[9],
              item11_anxiety_somatic: this.scores[10],
              item12_somatic_symptoms: this.scores[11],
              item13_general_somatic: this.scores[12],
              item14_genital: this.scores[13],
              item15_hypochondriasis: this.scores[14],
              item16_weight: this.scores[15],
              item17_insight: this.scores[16]
            };

            const submitRes = await submitHamd17(newAssessmentId, hamd17Data);

            if (submitRes.code !== 200) {
              throw new Error(submitRes.msg || '提交量表失败');
            }

            console.log('患者自评HAMD17量表提交成功');

            // 3. 保存到本地（用于离线查看）
            const testData = {
              scores: this.scores,
              totalScore: totalScore,
              severity: this.getSeverity(totalScore),
              testType: 'depression',
              testDate: new Date().toLocaleString('zh-CN'),
              assessmentId: newAssessmentId,
              isLocal: false
            };
            uni.setStorageSync('depressionTestData', testData);

            uni.hideLoading();
            uni.showToast({
              title: '提交成功',
              icon: 'success',
              duration: 1500
            });

            setTimeout(() => {
              this.navigateToReport();
            }, 1500);

          } else {
            // ========== 医生评估：提交到后端 ==========
            uni.showLoading({ title: '提交中...' });
            
            // 1. 如果没有评估ID，先创建评估记录
            if (!this.assessmentId) {
              console.log('医生评估模式，创建评估记录，患者ID:', this.patientId);
              const assessmentRes = await createAssessment(
                this.patientId,
                new Date().toISOString().split('T')[0], // 今天日期
                totalScore, // hamd_total
                0, // hama_total
                0  // ymrs_total
              );
              
              if (assessmentRes.code !== 200) {
                throw new Error(assessmentRes.msg || '创建评估记录失败');
              }
              
              this.assessmentId = assessmentRes.data.assessment_id;
              console.log('评估记录创建成功，ID:', this.assessmentId);
            }
            
            // 2. 提交HAMD17量表详情
            const hamd17Data = {
              item1_depression: this.scores[0],
              item2_guilt: this.scores[1],
              item3_suicide: this.scores[2],
              item4_sleep_initial: this.scores[3],
              item5_sleep_middle: this.scores[4],
              item6_sleep_late: this.scores[5],
              item7_activity: this.scores[6],
              item8_retardation: this.scores[7],
              item9_agitation: this.scores[8],
              item10_anxiety_psychic: this.scores[9],
              item11_anxiety_somatic: this.scores[10],
              item12_somatic_symptoms: this.scores[11],
              item13_general_somatic: this.scores[12],
              item14_genital: this.scores[13],
              item15_hypochondriasis: this.scores[14],
              item16_weight: this.scores[15],
              item17_insight: this.scores[16]
            };
            
            console.log('提交HAMD17数据:', hamd17Data);
            const submitRes = await submitHamd17(this.assessmentId, hamd17Data);
            
            if (submitRes.code !== 200) {
              throw new Error(submitRes.msg || '提交量表失败');
            }
            
            console.log('HAMD17量表提交成功');
            
            // 3. 同时保存到本地（用于离线查看）
            const testData = {
              scores: this.scores,
              totalScore: totalScore,
              severity: this.getSeverity(totalScore),
              testType: 'depression',
              testDate: new Date().toLocaleString('zh-CN'),
              assessmentId: this.assessmentId,
              isLocal: false
            };
            uni.setStorageSync('depressionTestData', testData);
            
            uni.hideLoading();
            uni.showToast({
              title: '提交成功',
              icon: 'success',
              duration: 1500
            });
            
            // 4. 跳转到查看报告页面
            setTimeout(() => {
              this.navigateToReport();
            }, 1500);
          }
          
        } catch (error) {
          uni.hideLoading();
          console.error('提交量表失败:', error);
          uni.showToast({
            title: error.message || '提交失败，请重试',
            icon: 'none',
            duration: 2000
          });
        }
      },
      
      // 获取严重程度
      getSeverity(totalScore) {
        if (totalScore < 8) {
          return '无抑郁症状';
        } else if (totalScore < 17) {
          return '轻度抑郁症状';
        } else if (totalScore < 24) {
          return '中度抑郁症状';
        } else {
          return '严重抑郁症状';
        }
      },
      
      // 跳转到报告页面
      navigateToReport() {
        // 计算总分
        const totalScore = this.calculateTotalScore();
        
        // 评定抑郁程度
        let severity = '';
        if (totalScore < 8) {
          severity = '无抑郁症状';
        } else if (totalScore < 17) {
          severity = '可能有抑郁症';
        } else if (totalScore < 24) {
          severity = '轻中度抑郁症状';
        } else {
          severity = '严重抑郁症状';
        }
        
        // 收集数据（使用系统中的用户信息）
        const testData = {
          scores: this.scores,
          totalScore: totalScore,
          severity: severity,
          testType: 'depression', // 抑郁量表类型标识
          testDate: new Date().toLocaleString('zh-CN') // 添加测试日期
        };
        
        // 存储数据到本地
        uni.setStorageSync('depressionTestData', testData);
        uni.setStorageSync('testData', testData);
        
        // 跳转到查看报告页面
        uni.switchTab({
          url: '/pages/chaKanBaoGao/chaKanBaoGao'
        });
      },
      
      // 计算总分
      calculateTotalScore() {
        let total = 0;
        for (let i = 0; i < 17; i++) {
          // 第14项（索引13）如果是3分则不计入总分
          if (i === 13 && this.scores[i] === 3) {
            continue;
          }
          total += this.scores[i];
        }
        return total;
      },
      
      // 改变评分
      changeScore(index, e) {
        this.scores[index] = parseInt(e.detail.value);
      },
      

    }
  }
  </script>

<style scoped>
  .container {
    display: flex;
    flex-direction: column;
    min-height: 100vh;
    background-color: #ffffff;
  }

  /* 顶部导航栏 */
  .header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    background-color: #4E5138; /* TEA LEAVES颜色 */
    padding: 0 30rpx;
    border-bottom: 1rpx solid #eee;
  }
  .back-button {
    width: 60rpx;
    height: 60rpx;
    display: flex;
    align-items: center;
    justify-content: center;
  }
  .back-icon {
    font-size: 36rpx;
    color: #fff;
  }
  .header-title {
    flex: 1;
    text-align: center;
  }
  .header-title text {
    font-size: 36rpx;
    font-weight: bold;
    color: #fff;
  }
  .header-right {
    width: 60rpx;
    display: flex;
    align-items: center;
    justify-content: center;
  }

  /* 主内容区域 */
  .content {
    flex: 1;
    padding: 30rpx;
    display: flex;
    flex-direction: column;
    align-items: center;
  }

  /* 问候语 */
  .greeting {
    display: flex;
    align-items: center;
    margin-bottom: 30rpx;
  }
  .greeting-text {
    font-size: 32rpx;
    color: #333;
    margin-right: 10rpx;
  }
  .avatar {
    width: 40rpx;
    height: 40rpx;
    border-radius: 50%;
  }

  /* 量表图片样式 */
  .scale-image-container {
    width: 100%;
    display: flex;
    justify-content: center;
    margin: 30rpx 0;
  }
  
  .scale-image {
    width: 100%;
    height: 300rpx;
    border-radius: 20rpx;
  }

  /* 卡通图片 */
  .illustration {
    width: 600rpx;
    height: 300rpx;
    background-color: #fff7e6;
    border-radius: 20rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    margin-bottom: 30rpx;
  }
  .dog-image {
    width: 200rpx;
    height: 200rpx;
  }

  /* 欢迎信息 */
  .welcome-text {
    text-align: left;
    margin-bottom: 60rpx;
  }
  .welcome-title {
    font-size: 40rpx;
    font-weight: bold;
    color: #333;
    display: block;
    margin-bottom: 20rpx;
  }
  .welcome-desc {
    font-size: 28rpx;
    color: #666;
    line-height: 50rpx;
  }

  /* 用户协议 */
  .agreement {
    display: flex;
    align-items: center;
    margin-bottom: 40rpx;
    width: 100%;
    justify-content: flex-start;
  }
  .checkbox-container {
    margin-right: 15rpx;
  }
  .checkbox {
    width: 30rpx;
    height: 30rpx;
    border: 2rpx solid #ccc;
    border-radius: 6rpx;
    display: flex;
    align-items: center;
    justify-content: center;
  }
  .checkbox.checked {
  background-color: #20b2aa;
  border-color: #20b2aa;
}

.checkbox.checked::after {
  content: '✓';
  color: #fff;
  font-size: 24rpx;
  font-weight: bold;
}
  .agreement-text {
    font-size: 28rpx;
    color: #20b2aa;
  }

  /* 开始按钮 */
  .start-button {
  width: 600rpx;
  height: 90rpx;
  line-height: 90rpx;
  background-color: #20b2aa;
  color: #fff;
  font-size: 36rpx;
  border-radius: 45rpx;
  margin-top: 40rpx;
}
  .start-button[disabled] {
    background-color: #ccc;
    color: #fff;
  }

  /* 问卷样式 */
  .questionnaire {
    background-color: #fff;
    min-height: 100vh;
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    z-index: 10;
  }

  .questionnaire-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 20rpx 30rpx;
    background-color: #ffffff;
    border-bottom: 1rpx solid #eee;
  }

  .questionnaire-title {
    font-size: 36rpx;
    font-weight: bold;
    color: #333;
  }

  .page-indicator {
    display: flex;
    align-items: center;
  }

  .page-number {
    width: 40rpx;
    height: 40rpx;
    border-radius: 50%;
    background-color: #eee;
    display: flex;
    align-items: center;
    justify-content: center;
    margin: 0 10rpx;
    font-size: 24rpx;
  }

  .page-number.active {
    background-color: #20b2aa;
    color: #fff;
  }
    
  /* 滚动到顶部按钮 */
  .scroll-top-button {
    position: fixed;
    bottom: 50rpx;
    right: 50rpx;
    width: 80rpx;
    height: 80rpx;
    border-radius: 50%;
    background-color: rgba(32, 178, 170, 0.9);
    color: #fff;
    font-size: 24rpx;
    line-height: 80rpx;
    text-align: center;
    z-index: 99;
  }
  
  /* 滚动条样式 */
  ::-webkit-scrollbar {
    width: 6px;
    height: 6px;
  }
  ::-webkit-scrollbar-track {
    background: #f1f1f1;
  }
  ::-webkit-scrollbar-thumb {
    background: #888;
    border-radius: 3px;
  }
  ::-webkit-scrollbar-thumb:hover {
    background: #555;
  }

  .save-icon {
    width: 40rpx;
    height: 40rpx;
  }

  .questionnaire-content {
    padding: 30rpx;
    background-color: #ffffff;
  }

  .patient-info {
    background-color: #fff;
    padding: 20rpx;
    border-radius: 10rpx;
    margin-bottom: 30rpx;
  }

  .section-title {
    font-size: 32rpx;
    font-weight: bold;
    color: #333;
    margin-bottom: 20rpx;
    display: block;
  }

  .info-item {
    display: flex;
    align-items: center;
    margin-bottom: 20rpx;
  }

  .info-label {
    font-size: 28rpx;
    color: #333;
    width: 120rpx;
  }

  .info-input {
    flex: 1;
    height: 80rpx;
    border: 1rpx solid #ddd;
    border-radius: 10rpx;
    padding: 0 20rpx;
    font-size: 28rpx;
  }

  .radio-group {
    flex: 1;
    display: flex;
  }

  .radio-label {
    display: flex;
    align-items: center;
    margin-right: 40rpx;
    font-size: 28rpx;
  }

  .test-items {
    background-color: #fff;
    padding: 20rpx;
    border-radius: 10rpx;
    margin-bottom: 30rpx;
  }

  .test-item {
    margin-bottom: 30rpx;
  }

  .item-title {
    font-size: 32rpx;
    font-weight: bold;
    color: #333;
    margin-bottom: 20rpx;
    display: block;
  }

  .score-options {
    display: flex;
    flex-direction: column;
  }

  .score-option {
    display: flex;
    align-items: center;
    padding: 20rpx;
    margin-bottom: 10rpx;
    background-color: #ffffff;
    border-radius: 10rpx;
    font-size: 28rpx;
  }

  /* 单选按钮颜色 */
  radio .wx-radio-input.wx-radio-input-checked {
    background-color: #20b2aa !important;
    border-color: #20b2aa !important;
  }
  
  radio .wx-radio-input.wx-radio-input-checked::before {
    color: #fff !important;
  }

  .navigation-buttons {
    display: flex;
    justify-content: space-between;
    margin-bottom: 30rpx;
  }

  .nav-button {
    flex: 1;
    height: 90rpx;
    line-height: 90rpx;
    background-color: #20b2aa;
    color: #fff;
    font-size: 36rpx;
    border-radius: 45rpx;
    margin: 0 20rpx;
  }

  .submit-button {
    width: 600rpx;
    height: 90rpx;
    line-height: 90rpx;
    background-color: #20b2aa;
    color: #fff;
    font-size: 36rpx;
    border-radius: 45rpx;
    margin: 0 auto 20rpx;
    display: block;
  }

  .confirm-checkbox {
    text-align: center;
    font-size: 28rpx;
    color: #666;
  }
</style>
